<template>
  <el-dialog
    v-model="createVisible"
    :title="operation == 'create' ? '添加运费模版' : '编辑运费模版'"
    @before-ok="createOk"
    @close="close(createRef)"
    width="1200px"
    top="100px"
  >
    <div v-loading="initLoading">
      <div style="width: 1050px">
        <el-form
          :model="createForm"
          ref="createRef"
          :rules="createRules"
          label-width="140px"
          size="default"
        >
          <el-form-item label="模板名称：" prop="name">
            <el-input
              v-model="createForm.name"
              placeholder="请输入模板名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="计费方式：" prop="type">
            <el-radio-group v-model="createForm.type">
              <template v-for="(item, index) in typeEnum" :key="index">
                <el-radio :label="item.value" border>{{ item.name }}</el-radio>
              </template>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="配送区域及运费：" prop="citys">
            <el-table style="width: 100%" :data="createForm.citys" border>
              <el-table-column prop="citys" label="可配送区域">
                <template #default="scope">
                  <span
                    v-if="
                      scope.row.citys &&
                      scope.row.citys.length ==
                        $utils.toArray(regionList).length
                    "
                    >全国</span
                  >
                  <template v-else>
                    <template
                      v-for="(province, index) in scope.row.treeData"
                      :key="index"
                    >
                      <span class="ml2 mb2 text-default fw"
                        >{{ province.name }}
                      </span>
                      <template
                        v-if="!province.isAllCitys && province.citys.length > 0"
                      >
                        [<template
                          v-for="(city, idx) in province.citys"
                          :key="idx"
                        >
                          <span class="text-grey">{{ city.name }}</span>
                          <span v-if="idx + 1 < province.citys.length"
                            >、</span
                          > </template
                        >]
                      </template>
                      ;
                    </template>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                :label="'首件' + typeEnum[createForm.type].unit ?? ''"
                width="100"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`citys[${scope.$index}].first`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="createForm.citys[scope.$index].first"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="运费 (元)" width="100">
                <template #default="scope">
                  <el-form-item
                    :prop="`citys[${scope.$index}].first_money`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="createForm.citys[scope.$index].first_money"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                :label="'续件' + typeEnum[createForm.type].unit ?? ''"
                width="100"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`citys[${scope.$index}].add_number`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="createForm.citys[scope.$index].add_number"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="续费（元）" width="100">
                <template #default="scope">
                  <el-form-item
                    :prop="`citys[${scope.$index}].add_money`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="createForm.citys[scope.$index].add_money"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="editSelectRegion('citys', scope.row, scope.$index)"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    confirm-button-text="确定"
                    cancel-button-text="不用了"
                    icon="WarningFilled"
                    icon-color="red"
                    title="确定删除吗？"
                    @confirm="delSelectRegion('citys', scope.$index)"
                  >
                    <template #reference>
                      <el-button link>删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <div class="">
              <el-button link type="primary" @click="addRegion('citys')"
                >添加可配送区域和运费</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="指定包邮：" prop="is_free_shipping">
            <el-radio-group v-model="createForm.is_free_shipping">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="free_shipping_citys"
            v-if="createForm.is_free_shipping == 1"
          >
            <el-table
              style="width: 100%"
              :data="createForm.free_shipping_citys"
              border
            >
              <el-table-column prop="free_shipping_citys" label="可包邮区域">
                <template #default="scope">
                  <span
                    v-if="
                      scope.row.citys &&
                      scope.row.citys.length ==
                        $utils.toArray(regionList).length
                    "
                    >全国</span
                  >
                  <template v-else>
                    <template
                      v-for="(province, index) in scope.row.treeData"
                      :key="index"
                    >
                      <span class="ml2 mb2 text-default fw"
                        >{{ province.name }}
                      </span>
                      <template
                        v-if="!province.isAllCitys && province.citys.length > 0"
                      >
                        [<template
                          v-for="(city, idx) in province.citys"
                          :key="idx"
                        >
                          <span class="text-grey">{{ city.name }}</span>
                          <span v-if="idx + 1 < province.citys.length"
                            >、</span
                          > </template
                        >]
                      </template>
                      ;
                    </template>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                :label="
                  '包邮' +
                  (createForm.type == 1
                    ? '件数'
                    : typeEnum[createForm.type].unit ?? '')
                "
                width="100"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`free_shipping_citys[${scope.$index}].number`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="
                        createForm.free_shipping_citys[scope.$index].number
                      "
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                label="满额包邮（元）"
                width="120"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`free_shipping_citys[${scope.$index}].money`"
                    :rules="{ required: true, trigger: 'blur' }"
                  >
                    <el-input
                      v-model="
                        createForm.free_shipping_citys[scope.$index].money
                      "
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="
                      editSelectRegion(
                        'free_shipping_citys',
                        scope.row,
                        scope.$index
                      )
                    "
                    >编辑</el-button
                  >
                  <el-popconfirm
                    confirm-button-text="确定"
                    cancel-button-text="不用了"
                    icon="WarningFilled"
                    icon-color="red"
                    title="确定删除吗？"
                    @confirm="
                      delSelectRegion('free_shipping_citys', scope.$index)
                    "
                  >
                    <template #reference>
                      <el-button link>删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <div class="">
              <el-button
                link
                type="primary"
                @click="addRegion('free_shipping_citys')"
                >添加可包邮区域</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="排序：" prop="sort">
            <el-input-number
              v-model="createForm.sort"
              :min="0"
              :max="10000"
              size="default"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <span class="flex center">
        <el-button @click="createVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="createOk(createRef)"
          :loading="btnLoading"
          :disabled="btnLoading"
          >确定</el-button
        >
      </span>
    </template>
    <selectRegion
      ref="selectRegionModalRef"
      :lists="regionList"
      @change="selectRegionChange"
    ></selectRegion>
  </el-dialog>
</template>
<script lang="ts">
export default {
  name: "createShippingTemplates",
};
</script>
<script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive, watch } from "vue";
import type { FormInstance } from "element-plus";
import type { Result, ResultError } from "@/types";
import { useConfig } from "@/store";
import { getTreeList } from "@/api/system/region";
import {
  getShippingTemplatesDetail,
  createShippingTemplates,
  updateShippingTemplates,
} from "@/api/store/shipping_templates";
import selectRegion from "./select-region.vue";
import { Console } from "console";

const configStore = useConfig();

const { proxy } = getCurrentInstance() as any;

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const createVisible = ref<boolean>(false);

const operation = ref<string>("create");

const operationId = ref<number>(0);

const createRef = ref<typeof FormInstance>();

const btnLoading = ref<boolean>(false);

const initLoading = ref<boolean>(true);

const typeEnum = ref(configStore.getEnumItem("store.shipping.TypeEnum"));

const createForm: any = ref({
  name: "",
  type: 1,
  citys: [],
  is_free_shipping: 0,
  free_shipping_citys: [],
  sort: 0,
});
const createRules: any = reactive({
  name: [{ required: true, message: "运费模版名称不能为空！" }],
  citys: [
    {
      type: "array",
      required: true,
      message: "请选择配送区域",
      min: 1,
    },
  ],
});

const toInit = () => {
  if (!operationId.value) {
    initLoading.value = false;
    return;
  }
  nextTick(() => {
    getShippingTemplatesDetail({ id: operationId.value })
      .then((res: Result) => {
        createForm.value.name = res.data.name;
        createForm.value.type = res.data.type.value;
        createForm.value.sort = res.data.sort;
        createForm.value.is_free_shipping = res.data.is_free_shipping;
        createForm.value.citys = checkCitys(res.data.citys);
        createForm.value.free_shipping_citys = checkCitys(res.data.free_citys);
        initLoading.value = false;
      })
      .catch((err: ResultError) => {
        $utils.errorMsg(err);
      });
  });
};

const checkCitys = (citys: any) => {
  citys.forEach((item: any) => {
    item.treeData = proxy?.$refs["selectRegionModalRef"]?.getTreeData(
      item,
      regionList.value
    );
  });
  return citys;
};

const regionList = ref<any>([]);

const cityCount = ref<number>(0);

const toInitRegion = () => {
  getTreeList()
    .then((res: Result) => {
      regionList.value = res.data.tree;
      cityCount.value = res.data.count.city;
      toInit();
    })
    .catch((err: ResultError) => {});
};

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    console.log(createForm.value, fields, valid);
    if (valid) {
      if (btnLoading.value) {
        return;
      }
      btnLoading.value = true;
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createShippingTemplates(createForm.value);
      } else {
        operationApi = updateShippingTemplates(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const selectRegionModalRef = ref<HTMLElement>();

const addRegion = (field: string) => {
  // 判断是否选择了全国
  var fieldCheck = createForm.value[field] || [],
    total = 0;
  fieldCheck.forEach((item: any) => {
    total += item.citys.length;
  });
  if (total != 0 && total >= cityCount.value) {
    $utils.errorMsg("已经选择了所有区域~");
    return false;
  }
  proxy?.$refs["selectRegionModalRef"]?.open(field, fieldCheck, -1);
};

const selectRegionChange = (res: any) => {
  var regionField = res.field;
  if (res.editIndex != -1) {
    createForm.value[regionField][res.editIndex].province = res.province;
    createForm.value[regionField][res.editIndex].citys = res.citys;
    createForm.value[regionField][res.editIndex].treeData = proxy?.$refs[
      "selectRegionModalRef"
    ]?.getTreeData(res, regionList.value);
    return false;
  }
  var formItem =
    regionField == "region"
      ? {
          province: res.province,
          citys: res.citys,
          treeData: proxy?.$refs["selectRegionModalRef"]?.getTreeData(
            res,
            regionList.value
          ),
          first: "",
          first_fee: "",
          add_number: "",
          add_money: "",
        }
      : {
          province: res.province,
          citys: res.citys,
          treeData: proxy?.$refs["selectRegionModalRef"]?.getTreeData(
            res,
            regionList.value
          ),
          money: "",
          number: "",
        };
  createForm.value[regionField].push(formItem);
};

const editSelectRegion = (field: string, item: any, index: number) => {
  let fieldCheck = createForm.value[field] || [];
  proxy?.$refs["selectRegionModalRef"]?.open(field, fieldCheck, index);
};

const delSelectRegion = (field: string, index: number) => {
  createForm.value[field].splice(index, 1);
};

const open = (id: number = 0) => {
  initLoading.value = true;
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  initLoading.value = true;
  nextTick(() => {
    toInitRegion();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  createForm.value.citys = [];
  createForm.value.free_shipping_citys = [];
  operationId.value = 0;
  createVisible.value = false;
  console.log(createForm.value);
};
watch(
  () => createForm.value,
  (val) => {
    // console.log(val);
  },
  { deep: true }
);

defineExpose({ open });
</script>


<style scoped>
</style>